<template>
  <div class="drill">
    <!-- 创作数据和部署 -->
    <div class="top">
      <!-- 聊天机器人 -->
      <div class="create">
        <el-card
          class="createCard"
          @click="toServer()"
          @mouseover="isRobot = true"
          @mouseout="isRobot = false"
        >
          <div class="createButton">
            <div class="logo">
              <img :src="isRobot ? fuwuqi2 : fuwuqi" alt="" />
            </div>
            <div class="main">选择服务器</div>
            <div class="round">添加服务资源</div>
            <div class="begin">
              开始
              <div class="logo2">
                <img :src="isRobot ? jiantou : jiantou2" alt="" />
              </div>
            </div></div
        ></el-card>
      </div>
    </div>

    <!-- 下边的数据集 -->
    <div class="down" v-loading="loading">
      <el-card class="allDataCard">
        <div class="tableTop">
          <img src="../../assets/../assets/image/云数据库.svg" alt="" />
          <div class="text">已有容器运行状态</div>
          <div class="input">
            <el-input
              v-model="search"
              size="large"
              style="width: 400px"
              placeholder="请输入服务器名称..."
            >
              <template #prefix>
                <img src="../../assets/image/放大镜.svg" alt="" /> </template
            ></el-input>
          </div>
        </div>
        <div class="downTable">
          <div style="height: 400px; overflow: auto">
            <el-table
              :data="filterTableData"
              class-name="elTable"
              style="height: 100%"
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="100" />
              </template>
              <el-table-column
                class-name="eltableColumn"
                label="服务器名称"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="IP"
                prop="container_status"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU型号"
                prop="container_status"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU数量"
                prop="container_status"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU"
                prop="container_status"
              />
              <el-table-column
                class-name="eltableColumn"
                label="内存"
                prop="container_status"
                width="130px"
              />
              <el-table-column
                class-name="eltableColumn"
                label="硬盘"
                prop="container_status"
                width="130px"
              />
              <el-table-column
                class-name="eltableColumn"
                label="分组"
                prop="container_status"
              />
              <!-- <el-table-column label="操作" prop="container_status" /> -->
              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    round
                    type="success"
                    @click="handleUpload(scope.$index, scope.row)"
                    >详情</el-button
                  >
                  <el-button
                    size="small"
                    round
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >

                  <el-button
                    size="small"
                    round
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-dialog v-model="dialogVisible">
            <el-form :model="editingRowData">
              <el-form-item label="模型名称">
                <el-input v-model="editingRowData.container_name" />
              </el-form-item>
            </el-form>
            <div slot="footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="nameChange()">确认</el-button>
            </div>
          </el-dialog>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {
  ElCard,
  ElDialog,
  ElInput,
  ElTable,
  ElTableColumn,
  ElButton,
  ElEmpty,
  ElMessageBox,
  ElMessage,
  ElForm,
  ElFormItem
} from 'element-plus'

import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { beginDrill, delModel, allContainer } from '../../api/model.js'
import fuwuqi2 from '../../assets/image/云服务器2.png'
import fuwuqi from '../../assets/image/云服务器.png'
import jiantou2 from '../../assets/image/箭头2.png'
import jiantou from '../../assets/image/箭头.png'
const router = useRouter()

const loading = ref(false)
const isRobot = ref(false) //鼠标进入

const search = ref('')
const editingRowData = ref({})
const dialogVisible = ref(false) // 编辑回显时的弹窗
let editIndex = -1 // 表示没有编辑的行
const tableData = reactive([
  {
    container_name: 'Tom',
    container_status: 'exited'
  }
])

// 编辑回显名字的确认
const nameChange = () => {
  // 判断是否有编辑的行
  if (editIndex !== -1) {
    tableData.splice(editIndex, 1, { ...editingRowData })
    dialogVisible.value = false
    // tableData.value = editingRowData.value  直接赋值会失败,因为直接赋值只是赋值,而这里需要一个对象
    tableData[editIndex] = Object.assign({}, editingRowData.value)

    ElMessage({
      type: 'success',
      message: '修改成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '修改失败!'
    })
  }
}
// 点击编辑
const handleEdit = (index, row) => {
  editIndex = index
  editingRowData.value = { ...row }
  dialogVisible.value = true
}

const handleUpdate = () => {
  if (editIndex !== -1) {
    tableData.splice(editIndex, 1, { ...editingRowData })
    dialogVisible.value = false
    // tableData.value = editingRowData.value  直接赋值会失败,因为直接赋值只是赋值,而这里需要一个对象
    tableData[editIndex] = Object.assign({}, editingRowData.value)

    ElMessage({
      type: 'success',
      message: '恭喜你训练成功 快去部署数据吧'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '修改失败!'
    })
  }
}

// 从后台拿现有模型列表
async function fetchData () {
  try {
    await allContainer().then(res => {
      console.log('容器列表的res', res)
      tableData.length = 0 // 清空tableData数组
      tableData.push(...res.data) // 将返回的数据添加到tableData数组中

      const styleOptions = {
        year: 'numeric',
        month: 'long', // 使用长格式，例如：'一月'
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }

      const dateRegex =
        /^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})\.\d+Z$/

      tableData.forEach(item => {
        const matches = dateRegex.exec(item.creat_time)
        if (matches) {
          const [, year, month, day, hour, minute, second] = matches
          item.creat_time = new Date(
            Date.UTC(
              Number(year),
              Number(month) - 1,
              Number(day),
              Number(hour),
              Number(minute),
              Number(second)
            )
          )
            .toLocaleString(undefined, styleOptions)
            .replace(/\//g, '-')
        }
      })

      console.log('tableData', tableData)
    })
  } catch (error) {
    console.error('从后台拿现有模型列表失败', error)
  }
}

const toServer = () => {
  router.push('./createServer')
}

// 搜索功能
const filterTableData = computed(function () {
  return tableData.filter(function (data) {
    return (
      !search.value ||
      data.container_name.toLowerCase().includes(search.value.toLowerCase())
    )
  })
})

// 删除功能
const handleDelete = async (index, row) => {
  ElMessageBox.confirm(`是否删除名称为 ${row.container_name} 数据 ?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        await delModel({
          container_name: row.container_name
        })

        tableData.splice(index, 1)
        loading.value = false
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      } catch (error) {
        console.error('Failed to delete data:', error)
        ElMessage({
          type: 'error',
          message: '删除失败'
        })
      }
    })
    .catch(() => {})
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.drill {
  display: flex;
  margin: 0 auto;
  flex-direction: column;
  .top {
    padding: 20px;
    display: flex;
    width: 100%;
    justify-content: center;
    .create {
      padding: 20px;
      width: 50%;
      position: relative;
      .logo {
        position: absolute;
        top: 80px;
        left: 80px;
        img {
          width: 80px;
          height: 80px;
        }
      }
      .logo2 {
        position: absolute;
        top: 80px;
        left: 80px;

        img {
          width: 100px;
          height: 100px;
        }
      }
      .main {
        font-size: 26px;
        font-weight: bold;
        position: absolute;
        top: 90px;
        left: 210px;
      }
      .round {
        font-size: 20px;
        position: absolute;
        top: 140px;
        left: 210px;
        color: #ccc;
      }
      .begin {
        font-size: 26px;
        font-weight: bold;
        position: absolute;
        top: 200px;
        left: 210px;
      }
    }

    .create :hover {
      cursor: pointer;
      background: #91d5ff;
      .main {
        color: #fff;
      }
      .begin {
        color: #fff;
      }
      .round {
        color: #ffffffe2;
      }
    }
  }

  .down {
    padding: 0 35px 0 35px;
    :deep(.allDataCard) {
      width: 100%;
      height: 400px;
    }
    .tableTop {
      font-weight: bold;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 40px;
      .input {
        margin: 10px 0 0 50px;
        img {
          width: 21px;
          height: 21px;
        }
      }
      img {
        width: 65px;
        height: 65px;
      }
      .text {
        font-size: 22px;
        font-weight: bold;
        margin: 10px 0 0 50px;
      }
    }
    .downTable {
      height: 500px;
      width: 100%;
      position: relative;
      img {
        width: 20px;
        height: 20px;
      }
      .elTable {
        position: absolute;
        top: 10%;

        :deep(.eltableColumn) {
          color: black;
        }
      }
    }
  }
  :deep(.createCard) {
    height: 400px;
  }

  :deep(.el-popup-parent--hidden) {
    width: 100%;
  }
}

@media screen and (max-width: 1100px) {
  .drill .top .create {
    .logo {
      position: absolute;
      left: 50px;
      img {
        width: 80px;
        height: 80px;
      }
    }
    .main {
      font-size: 24px;
      font-weight: bold;
      position: absolute;
      top: 90px;
      left: 180px;
    }
    .round {
      font-size: 18px;
      position: absolute;
      top: 140px;
      left: 120px;
      color: #ccc;
    }
    .begin {
      font-size: 24px;
      font-weight: bold;
      position: absolute;
      top: 200px;
      left: 180px;
    }
  }
}

@media screen and (min-width: 3900px) {
  .drill {
    width: 3000px;
  }
}
</style>
